<template>
  <view class="content">
    <view class="containerBase">
      <view>
        <view>audio source:</view>
        <audio id="exteneraudeo1" ref="exteneraudeo1" src="https://storage.zego.im/demo/tonight.m4a" playsinline controls loop></audio>
        <!-- <view style="display:flex; align-items: center"
          >音量 <slider block-size="18" backgroundColor="#999999" style="width: 50%" @change="sliderChange" min="0" max="100" value="100" />
        </view> -->
        <!-- <audio id="exteneraudeo2" ref="exteneraudeo2" src="https://storage.zego.im/demo/oldman.m4a" muted playsinline controls loop crossOrigin="anonymous"></audio> -->
        <!-- <view style="display:flex; align-items: center"
          >音量 <slider block-size="18" backgroundColor="#999999" style="width: 50%" @change="sliderChange" min="0" max="100" value="100" />
        </view> -->
      </view>
      <video v-if="localStream" ref="localVideo" id="localVideo" :controls="controls" autoplay></video>
      <video v-if="isShowMixStream" ref="mixVideo" id="mixVideo" :controls="controls" autoplay></video>
      <video v-if="secondStream" ref="secondVideo" id="secondVideo" :controls="controls" autoplay muted></video>

      <video v-for="item in remoteStreams" :controls="controls" :ref="item.id" :id="item.id" :key="item.id" autoplay></video>
    </view>
    <view class="index-container">
      <view class="input-container">
        <input v-model="roomID" placeholder="请输入房间 ID" placeholder-style="color: #b3b3b3; font-size: 14px;" class="room-input" />
        <text class="tip"></text>
      </view>
      <view class="button-container">
        <view>推拉流:</view>
        <button @click="openRoom(1)" class="roomBtn">加入房间(推流)</button>
        <button @click="openRoom(0)" class="roomBtn">加入房间(不推流)</button>
        <button @click="screenShare" class="roomBtn">屏幕共享</button>
        <button @click="logout" class="roomBtn">退出房间</button>
        <br />
        <button @click="mixStream" class="roomBtn">混流</button>
        <button @click="mixAudioStream" class="roomBtn">混音频流</button>
        <button @click="addPublishCdnUrl" class="roomBtn">转推cdn</button>
        <br />
        <view>
          <view>混流: 先推流，然后点击混流。 效果: 将多条流按照调用要求合成一条流</view>
          <view>混音频流: 先推流，然后播放音频，然后点击混流。 效果: 对正在推的流添加背景音乐或音效</view>
        </view>
        <br />
      </view>
    </view>
  </view>
</template>

<script>
import { Express } from "../../utils/h5/h5_common"
import flvjs from "flv.js"
import Hls from "hls.js"
import videojs from "video.js"

export default {
  data() {
    return {
      controls: false,
      roomID: "126",
      localStream: null,
      remoteStreams: [],
      express: null,

      devices: {},
      microphone: null,
      camera: null,
      speaker: null,
      isShowMixStream: false,
      secondStream: null
    }
  },
  watch: {
    remoteStreams(newVal, oldVal) {
      this.renderRemoteVideo()
    }
  },

  methods: {
    async openRoom(type) {
      await this.express.login(this.roomID)
      if (type !== 0) {
        this.localStream = await this.express.createStream()
        this.$nextTick(() => {
          this.$refs.localVideo.$refs.video.srcObject = this.localStream // 对 video组件内真实的video元素 进行赋值
          console.log("mytag this.express", this.express)
        })
      }
    },

    async screenShare() {
      const createOption = {
        screen: true
      }
      this.secondStream = await this.express.createSecondStream(createOption)

      this.$nextTick(() => {
        this.$refs.secondVideo.$refs.video.srcObject = this.secondStream
        console.log("mytag this.express", this.express)
      })
    },

    renderRemoteVideo() {
      this.$nextTick(() => {
        this.remoteStreams.forEach((streamItem) => {
          this.$refs[streamItem.id][0].$refs.video.srcObject = streamItem
        })
      })
    },

    async logout() {
      if (!this.express.hasLogin) {
        uni.showToast({
          title: "尚未登录",
          duration: 2000,
          icon: "none"
        })
        return
      }
      this.express.logout()
      this.localStream = null
      this.remoteStreams = []
    },

    async getDevice() {
      this.devices = await this.express.enumDevices()
      if (this.devices.cameras && this.devices.cameras.length) {
        this.camera = this.devices.cameras[0].deviceID
      }
      if (this.devices.speakers && this.devices.speakers.length) {
        this.speaker = this.devices.speakers[0].deviceID
      }
      if (this.devices.microphones && this.devices.microphones.length) {
        this.microphone = this.devices.microphones[0].deviceID
      }
      console.log("mytag this.devices.microphones", this.devices.microphones)
      console.log("mytag this.microphone", this.microphone)
    },

    async initExpress() {
      this.express = new Express()
      this.express.init()
      this.remoteStreams = this.express.remoteStreams
      await this.express.checkSystemRequirements()
      await this.getDevice()
      window.express = this.express
    },
    // 混音频流
    async mixAudioStream() {
      // console.log("mytag this.$refs.exteneraudeo1.$refs.audio", this.$refs.exteneraudeo1.$refs.audio);
      this.express.zegoEngine.startMixingAudio(this.express.streamID, [this.$refs.exteneraudeo1.$refs.audio])
    },
    // 混视频流
    async mixStream() {
      try {
        this.isShowMixStream = true
        const { flvURL, rtmpURL, hlsURL, streamID } = await this.express.mixStream()
        console.log("mytag  flvURL, rtmpURL, hlsURL, streamID",  flvURL, rtmpURL, hlsURL, streamID);
        // this.express.getPlayStream({streamID})

        // Hls播放器
        if (Hls.isSupported()) {
          console.log("mytag hlsURL", hlsURL)
          this.hls = new Hls()
          this.hls.loadSource(hlsURL)
          this.hls.attachMedia(this.$refs.mixVideo.$refs.video)
          
          this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
            console.log("加载成功")
            this.$refs.video.play()
          })
          this.hls.on(Hls.Events.ERROR, (event, data) => {
            console.log("加载失败")
          })
        }

        //  flv播放器
        // this.$nextTick(() => {
        //   if (flvjs.isSupported()) {
        //     const flvPlayer = flvjs.createPlayer({
        //       type: "flv",
        //       url: flvURL
        //     })
        //     flvPlayer.attachMediaElement(this.$refs.mixVideo.$refs.video)
        //     flvPlayer.load()
        //   }
        // })
        

        // rtmp播放器 videojs
        // this.$refs.mixVideo.$refs.video.src = rtmpURL


      } catch (error) {
        console.log("mytag error", error)
      }
    },
    // 转推cdn
    async addPublishCdnUrl() {
      this.isShowMixStream = true
      const result = await this.express.zegoEngine.addPublishCdnUrl(this.express.streamID, "rtmp://publish-qcloud-test.zego.im/live/" + this.express.streamID)

      console.log("mytag cdm rtm ", "http://play-qcloud-test.zego.im/live/" + this.express.streamID + ".m3u8")

      if (Hls.isSupported()) {
        setTimeout(async () => {
          let hlsUrl = "http://play-qcloud-test.zego.im/live/" + this.express.streamID + ".m3u8"
          this.hls = new Hls()
          const res = await this.hls.loadSource(hlsUrl)
          console.log("mytag res in loadSourse", res, hlsUrl)
          this.hls.attachMedia(this.$refs.mixVideo.$refs.video)
        }, 3000)

        // this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
        //   console.log("加载成功")
        //   this.$refs.video.play()
        // })
        // this.hls.on(Hls.Events.ERROR, (event, data) => {
        //   console.log("加载失败")
        // })
      }
      if (result.errorCode == 0) {
        console.log("add push target success")
      } else {
        console.log("add push target fail " + result.errorCode)
      }
    }
  },

  async mounted() {
    this.$refs.exteneraudeo1.$refs.audio.setAttribute("crossOrigin", "anonymous")
    this.initExpress()
  },
  beforeDestroy() {}
}
</script>

<style>
.containerBase {
  height: 73vh;
  max-height: 500px;
  padding: 10rpx;
}

video {
  width: 45vw;
  height: 45vw;
  max-width: 200px;
  max-height: 200px;
  margin: 5rpx;
}

.index-container {
  border-top: 1px slategrey solid;
}
.input-container {
  text-align: center;
}
.button-container {
  border-top: 1px slategrey solid;
  padding: 5px 0 0 5px;
}
.room-input {
  height: 80rpx;
  border-bottom: 1px solid rgba(13, 112, 255, 0.5);
}
button[type="primary"] {
  background-color: red;
}

.roomBtn {
  display: inline-block;
  margin: 1vw;
  font-size: 20rpx;
  background: rgba(13, 112, 255, 0.5);
  color: #fff;
  overflow: visible;
}
</style>
